import {
	getStorageSync,
	removeStorageSync,
	hideLoading,
	showLoading,
	showToast,
} from "@/utils/index";
var Fly = require("flyio/dist/npm/wx");
var fly = new Fly();
// 设置超时
// fly.config.timeout = 7000;

// 添加请求拦截器
fly.interceptors.request.use((request) => {
	// 给所有请求添加自定义header
	request.headers["X-Access-Token"] = getStorageSync("token")
	return request;
});


//封装请求
function sendRequest() {
	return {
		//成功回调
		_sucCallback: null,
		//失败回调
		_failCallback: null,
		//默认请求路径
		_method: "GET",
		//默认请求体
		_data: {},
		//默认请求头
		_header: {
			"Content-Type": "application/json",
		},
		_url: "",
		send: function() {
			showLoading({
				title: "加载中...",
			});
			fly
				.request(this._url, this._data, {
					method: this._method,
					headers: this._header,
				})
				.then((res) => {
					hideLoading();
					//成功执行
					let error = httpHandlerError(res, this._failCallback);
					if (error) return;
					this._sucCallback(res);
				})
				//失败执行
				.catch((res) => {
					console.log(res);
					hideLoading();
					httpHandlerError(res, this._failCallback);
					this._failCallback(res);
				});

			return this;
		},
		success: function(callback) {
			this._sucCallback = callback;
			return this;
		},
		fail: function(callback) {
			this._failCallback = callback;
			return this;
		},
		url: function(url) {
			this._url = url;
			return this;
		},
		data: function(data) {
			this._data = data;
			return this;
		},
		method: function(method) {
			this._method = method;
			return this;
		},
		header: function(header) {
			this._header = header;
			return this;
		},
	};
}

/**
 * info 请求完成后返回信息
 * callBack 回调函数
 * errTip 自定义错误信息
 */
function httpHandlerError(info, callBack) {
	// hideLoading();
	/** 请求成功，退出该函数 可以根据项目需求来判断是否请求成功。这里判断的是status为200的时候是成功 */
	let haveError = true;
	var errTip = "";
	switch (info.status) {
		case 200:
			haveError = false;
			break;
		case 400:
			errTip = "请求错误(400)";
			break;
			//报错401跳转到登录页面
		case 401:
			haveError = false;
			errTip = "当前用户未登录";
			removeStorageSync("userInfo");
			removeStorageSync('token')
			uni.reLaunch({
				url: "/pages/LoginPages/mylogin/main",
			});
			break;
		case 403:
			errTip = "拒绝访问(403)";
			break;
		case 404:
			errTip = "请求出错";
			break;
		case 408:
			errTip = "请求超时(408)";
			break;
		case 500:
			errTip = "服务器错误(500)";
			break;
		case 501:
			errTip = "服务未实现(501)";
			break;
		case 502:
			errTip = "网络错误(502)";
			break;
		case 503:
			errTip = "服务不可用(503)";
			break;
		case 504:
			errTip = "网络超时(504)";
			break;
		case 505:
			errTip = "HTTP版本不受支持(505)";
			break;
		default:
			errTip = `连接出错(${info.status})!`;
	}
	if (haveError) {
		/** 发生错误信息时，如果有回调函数，则执行回调 */
		if (callBack) {
			callBack(info);
			showToast({
				title: errTip,
				image: "../../static/images/failure.png",
				duration: 1500,
			});
		}
	}
	return haveError;
}

/**
 * request服务封装
 */
export default {
	sendRequest,
};
